<?php
/**
 * 公共消息服务器
 * 负责消息转发
 */

use \GatewayWorker\Lib\Gateway;

require_once __DIR__ . './../ProtocolApi/ProtocolApi.php';
require_once __DIR__ . './../ProtocolApi/Status.php';
require_once __DIR__ . './../Common/SessionMessage.php';
require_once __DIR__ . './../DbModel/UserDb.php';
require_once __DIR__ . '/PublicServerDb.php';


class PublicServer
{

    //处理消息
    public function receiveMessage($message)
    {

        $msghead = $message['head'];
        $client_id = $message['client_id'];
        $message = $message['msg'];

        if(!empty($message['token'])){
            UserDb::getTokenToUserDetail($client_id,$message['token']);
            return true;
        }

        switch ($msghead) {

            case ProtocolApi::$USER_LOGIN:
                $this->userLogin($client_id, $message);
                break;

            case ProtocolApi::$USER_REGISTER:
                $this->userRegister($client_id, $message);
                break;
        }

    }

    /**
     * @param $client_id
     * @param $message
     * @return bool
     * @throws Exception
     */
    private function userLogin($client_id, $message)
    {
        $usernmae = $message['username'];
        $password = $message['password'];
        $user = PublicServerDb::userLogin($usernmae);

        if (!$user) {
            $message=ProtocolApi::returnMessage(ProtocolApi::$STATUS_ERROR,'用户不存在');
            Gateway::sendToClient($client_id, $message);
            return true;
        }

        if($user['password']!=$password){
            $message=ProtocolApi::returnMessage(ProtocolApi::$STATUS_ERROR,'密码错误');
            Gateway::sendToClient($client_id, $message);
            return true;
        }

        $token=$user['user_id'].'_'.md5($usernmae.$password.uniqid());
        $user['token']=$token;
        SessionMessage::updateClientidToSession($client_id,'player_id',$user['user_id']);
        SessionMessage::updateClientidToSession($client_id,'token',$user['token']);
        SessionMessage::updateClientidToSession($client_id,'player_info',$user);
        $msg = Status::returnMessage(Status::$StatusOK, ['token'=>$token]);
        DataBase::Table('GAME_USER')->where('user_id='.$user['user_id'])->update(['token'=>$token]);
        $message=ProtocolApi::returnMessage(ProtocolApi::$USER_LOGIN,$msg);
        Gateway::bindUid($client_id, $user['user_id']);
        Gateway::sendToClient($client_id, $message);
        return true;
    }

    /**
     * 玩家注册
     * @param $message
     */
    private function userRegister($client_id, $message)
    {

    }
}